<?php
 /******************************************************************************
 *   GunCMS is an avid supporter of open source software. This is the appropriate 
 *   option if you are creating an open source application with a license 
 *   compatible with the GNU GPL license v3.
 *   For details http://www.gnu.org/licenses/gpl.html
 *   DO NOT USE FOR COMMERCIAL WITHOUT PERMISSION
 *
 * GunCMS Version 1.0.3
 * Copyright(c) 2009-2010, T & L GdbR
 * info@guncms.de
 * 
 * http://www.guncms.de
 ********************************************************************************/
class FgcmsCheckout {
	var $db;
 	var $smarty;	
	public function __construct($db, $smarty) {
		//contructor function
		$this->db = $db;
		$this->smarty = $smarty;
	}
	
	/* Assigning the content related to the category_id to the 
	 * Smarty-Variable 'PAGE'. Because using ezSql, PAGE is a pointer!
	 * One should be aware of this fact, when PAGE is used in the 
	 * Smarty-Templates. Output is generated ba: {$PAGE->page_content}.
	 */ 
	public function process($object,$subtotal) {
		if(isset($_POST["act"]) && $_POST["act"] != ""){
			if($_POST["act"] == "del")
				$this->del_basket();
			else if($_POST["act"] == "shipping_address"){
				FgcmsCheckoutShipping::save_shipping_address();
			}	
			else if($_POST["act"] == "shipping"){
				FgcmsCheckoutShipping::save_shipping();
			}
			else if($_POST["act"] == "payment_address"){
				FgcmsCheckoutPayment::save_payment_address();
			}	
			else if($_POST["act"] == "payment"){
				FgcmsCheckoutPayment::save_payment();
			}
			else if($_POST["act"] == "order"){
				$this->save_order();
			}
		}	
		if($object=='shipping' || $object=='shipping_address')
			FgcmsCheckoutShipping::view_shipping();	
		else if($object=='payment' || $object=='payment_address')
			FgcmsCheckoutPayment::view_payment();	
		else if($object=='order_confirm')
			$this->view_order_confirm($subtotal);
		else if($object=='process_paypal')
			$this->method_paypal();
		else if($object=='paypal_success')
			$this->paypal_success();
		else if($object=='paypal_failure')
			$this->paypal_failure();					
	}
	
	public function del_basket() {
	
		$addproductslist = array();
		$total = $_SESSION['total'];
		$dem ="";
		$testses = "";
		if($_POST["act"] == "del") {
			for($i=1;$i< $total+1;$i++) {
				if($_POST["quantity{$i}"] != 0 && ctype_digit($_POST["quantity{$i}"])) {
					$arrproduct = split("[,]",$_SESSION['pro'.$i]);
					$_SESSION['pro'.$i] = $arrproduct[0].",".$_POST["quantity{$i}"];
				}	
			}
			$check = "";
			for($i=1;$i< $total+1;$i++) {
				if(isset($_POST["rev{$i}"]) && $_POST["rev{$i}"]!= "") {
					if($_POST["rev{$i}"] == $i) {
						for($j=$i+1;$j< $total+1;$j++) {	
							//$countses = $j + $testses;
							if($j > $testses) {	
								if($testses >= $total) {
									$testses = $total;
								}	
								if(isset($_SESSION['pro'.$j]) && $_SESSION['pro'.$j] != "" && $_POST["rev{$j}"] == "" ) {
									$_SESSION['pro'.$i] = $_SESSION['pro'.$j];
									$testses = $j;
									$check = 1;
									break;
								}
							}
						}//end for
						$dem ++;	
					}
				} else {
					if($check == 1)	{	
						for($j=$i+1;$j< $total+1;$j++) {	
							if($testses >= $total) {
								$testses = $total;
							}
							if($j > $testses) {
								//$countses = $j + $testses;			
								if(isset($_SESSION['pro'.$j]) && $_SESSION['pro'.$j] != "" && $_POST["rev{$j}"] == "" ) {
									$_SESSION['pro'.$i] = $_SESSION['pro'.$j];
									$testses = $j;
									//$check = 1;
									break;
								}
							}
						}//end for					
					}//end if
				}
				
			}//end for
			
			$h = $total-$dem +1;
			for($c=$h;$c< $total+1;$c++) {
				unset($_SESSION['pro'.$c]);
				$_SESSION['total']--;
				//break;
			}
			
			header("Location: ./?page=checkout_basket");	
		}
	}
	
	public function view_basket() {
		$addproductslist = array();
		$total = $_SESSION['total'];
		$dem ="";
		$testses = "";
		
		$subtotal = 0;
		for($t=1;$t<= $total;$t++) {
			$arrproduct = split("[,]",$_SESSION['pro'.$t]);
			$product = FgcmsProductBean::getProductbyId($this->db, $arrproduct[0]);
			$product->quantity = $arrproduct[1];
			if(isset($product->featured_new_products_price)&&$product->featured_new_products_price!="")
				$pro_price = $product->featured_new_products_price;
			else if(isset($product->specials_new_products_price)&&$product->specials_new_products_price!="")
				$pro_price = $product->specials_new_products_price;	
			else
				$pro_price = $product->product_price;		
			$product->thumb_image = UPLOAD_PRODUCT_THUMB.$product->product_thumbnail;	
			$price = $pro_price * $arrproduct[1];
			$product->tax = $product->tax;
			$tax = $price*$product->tax/100;
			$totalcost = ($price+$tax);
			$product->total = number_format($totalcost,2, '.', ',');
			$subtotal = $subtotal +$totalcost;
			$addproductslist['pro_'.$t] = $product;
		}
		$subtotal = number_format($subtotal,2, '.', ',');
		$this->smarty->assign("SUBTOTAL", $subtotal);
		$this->smarty->assign("BASKET", $addproductslist);
		return $subtotal;
	}
	
	/* view order confirm form
	 * @param integer $subtotal
	 */
	public function view_order_confirm($subtotal) {
		$information = FgcmsCustomerBean::getCustomerById($this->db,$_SESSION['cust_id']);
		$total = $subtotal + $_SESSION['delivery']['delivery_cost'];
		//gets delivery cost from session
		$information->delivery_cost = $_SESSION['delivery']['delivery_cost'];
		//gets delivery shipping method from session
		$information->shipping_method = $_SESSION['delivery']['shipping_method'];
		$_SESSION['amount'] = $total;
		$this->smarty->assign("TOTAL", $total);
		$this->smarty->assign("SALESORDER", $information);
		
	}
	
	public function save_order() {
			$information = FgcmsCustomerBean::getCustomerById($this->db,$_SESSION['cust_id']);
			
			$addproductslist = array();
			$total = $_SESSION['total'];
			$dem ="";
			$testses = "";
			
			$subtotal = 0;
			for($t=1;$t<= $total;$t++) {
				$arrproduct = split("[,]",$_SESSION['pro'.$t]);
				$product = FgcmsProductBean::getProductbyId($this->db, $arrproduct[0]);
				$product->quantity = $arrproduct[1];
				$product->total = number_format(($product->product_price * $arrproduct[1]),2, '.', ',');
				$productcost = $product->product_price * $arrproduct[1];
				$subtotal = $subtotal + $productcost;
				$addproductslist['pro_'.$t] = $product;
			}
			$orderinfo = array('customer_id' => $_SESSION['cust_id'],
						  'delivery_gender' => $information->delivery_gender,
					  	  'delivery_firstname' => $information->delivery_firstname,
						  'delivery_lastname' => $information->delivery_lastname,
						  'delivery_company' => $information->delivery_company,
						  'delivery_street_address' => $information->delivery_street_address,
						  'delivery_city' => $information->delivery_city,
						  'delivery_postcode' => $information->delivery_postcode,
						  'delivery_state' => $information->delivery_state,
						  'delivery_country' => $information->delivery_country,
						  'delivery_country_name' => $information->delivery_country_name,
						  'delivery_telephone' => $information->delivery_telephone,
						  'delivery_email_address' => $information->delivery_email_address,
						  'shipping_method' => $_SESSION['delivery']['shipping_method'],
						  'delivery_cost' => $_SESSION['delivery']['delivery_cost'],
						  'notes' => $_SESSION['delivery']["notes"],
						  'billing_gender' => $information->billing_gender,
					  	  'billing_firstname' => $information->billing_firstname,
						  'billing_lastname' => $information->billing_lastname,
						  'billing_company' => $information->billing_company,
						  'billing_street_address' => $information->billing_street_address,
						  'billing_city' => $information->billing_city,
						  'billing_postcode' => $information->billing_postcode,
						  'billing_state' => $information->billing_state,
						  'billing_country' => $information->billing_country,
						  'billing_country_name' => $information->billing_country_name,
						  'billing_telephone' => $information->billing_telephone,
						  'billing_email_address' => $information->billing_email_address,
						  'payment_method' => $_SESSION['billing']['payment_method'],
						  'currency' => $_POST["currency"],
						  'currency_value' => $_POST["currency_value"]);	
			$information = FgcmsCustomerBean::getCustomerById($this->db,$_SESSION['cust_id']);
			$settings = FgcmsSettingsBean::get_all_settings($this->db);
			//Payment with Vorkasse
			if($billing["payment_method"]!="Paypal"){		  
				$res = FgcmsCheckoutBean::save_order_list($this->db,$orderinfo,$addproductslist);
				$this->send_mail_order_to_admin($orderinfo,$addproductslist,$information->customer_email, $settings);
				if($res>0){			
					unset($_SESSION['delivery']); 
					unset($_SESSION['billing']);  
					for($t=1;$t<= $total;$t++){
						unset($_SESSION['pro'.$t]);  
					}
					unset($_SESSION['total']); 
					header("Location: ./?page=checkout_finish");	 
				}
				
			} else {
				//Start Payment with Paypal
				$res = FgcmsCheckoutBean::save_order_list($this->db,$orderinfo,$addproductslist);
				$this->send_mail_order_to_admin($orderinfo,$addproductslist,$information->customer_email, $settings);
				if($res>0){			
					unset($_SESSION['delivery']); 
					unset($_SESSION['billing']);  
					for($t=1;$t<= $total;$t++){
						unset($_SESSION['pro'.$t]);  
					}
				}
				$orderinfo['orderid']=$res;
				$_SESSION['orderinfo'] = $orderinfo;
				header("Location: ./?page=checkout_process_paypal");	
				//$this->method_paypal();
			}	
	}
	
	/*send order email to admins and customer
	 * $orderinfo - information of customer
	 * $addproductslist - products
	 * $customer_email - customer email
	 */
	public function send_mail_order_to_admin($orderinfo,$addproductslist,$customer_email, $settings){
			//host and email from are load from config
			$host = $_SERVER['HTTP_HOST'].FOLDER_HOST;
			$from = FROMMAIL;
			//sender name
			$fromname = "T & L Tec GdbR";
			$subject = "GunWebshop Checkout Order";
			$this->smarty->assign("PRODUCT_ORDER", $addproductslist);
			$this->smarty->assign("INFORMATION", $orderinfo);
			$this->smarty->assign("SHOP_SETTINGS", $settings);
			
			//load all admin emails
			$email = FgcmsCheckoutBean::get_all_email_receiver($this->db);
			
			//load email template for admin
			$adminEmailTemplate = $this->smarty->fetch("checkout/email_order_to_admin.tpl");
			//load email template for customer
			$customerEmailTemplate = $this->smarty->fetch("checkout/email_order.tpl");
			$header = "Content-type: text/html\r\nFrom: $from\r\nReply-to: $from";
			FgcmsEmail::send_mail($customer_email, $customerEmailTemplate, $subject, $from, $fromname, false);
			
			
			if($email!=""){
				foreach($email as $item){
					FgcmsEmail::send_mail($item->user_email, $adminEmailTemplate, $subject, $from, $fromname, false);
				}
			}
	}
	
	/*
	 *Paypal 
	 */
	public function method_paypal(){
			include_once ('includes/plugins/webshop/controller/payment/Paypal.php');
			// Create an instance of the paypal library
			$orderinfo = $_SESSION['orderinfo'];
			$myPaypal = new Paypal($this->db, $this->smarty);
			
			// Specify your paypal email
			$email = FgcmsConfigBean::getconfig($this->db,"EMAIL_PAYPAL");
			$myPaypal->addField('business', $email->value);
			
			// Specify the currency
			$myPaypal->addField('currency_code', 'EUR');
			
			// Specify the url where paypal will send the user on success/failure
			$myPaypal->addField('return', 'http://'.HOST.'?page=checkout_paypal_success');
			$myPaypal->addField('cancel_return', 'http://'.HOST.'?page=checkout_paypal_failure');
			
			// Specify the url where paypal will send the IPN
			$myPaypal->addField('notify_url', 'http://'.HOST.'payment/paypal_ipn.php');
			// Specify the product information
			$myPaypal->addField('item_name', 'Webshop');
			$myPaypal->addField('amount', $_SESSION['amount']);
			$myPaypal->addField('item_number', '001');
			
			// Specify any custom value
			$myPaypal->addField('custom', 'muri-khao');
			
			// Enable test mode if needed
			//$myPaypal->enableTestMode();
			unset($_SESSION['total']); 
			// Let's start the train!
			$myPaypal->submitPayment();
	}	
	
	/*
	 *Paypal 
	 */	
	public function paypal_success(){
		if(isset($_SESSION['orderinfo'])){
			$info = $_SESSION['orderinfo'];
			if(isset($info['orderid']) && $info['orderid'] !=""){
				$res = FgcmsCheckoutBean::update_pay_success($this->db,$info['orderid']);	
				unset($_SESSION['orderinfo']);
			}
		}	
	}
	
	/*
	 *Paypal 
	 */	
	public function paypal_failure(){
		if(isset($_SESSION['orderinfo'])){
			$info = $_SESSION['orderinfo'];
			if(isset($info['orderid']) && $info['orderid'] !=""){
				unset($_SESSION['orderinfo']);
				
			}
		}//end if	
	}//end	
}
?>
